package com.nbcio.modules.erp.voucher.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nbcio.common.mybatis.core.page.PageQuery;
import com.nbcio.common.mybatis.core.page.TableDataInfo;
import com.nbcio.modules.erp.voucher.domain.ErpAccount;
import com.nbcio.modules.erp.voucher.mapper.ErpAccountMapper;
import com.nbcio.modules.erp.voucher.service.IErpAccountService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 会计科目服务实现
 */
@Service
public class ErpAccountServiceImpl extends ServiceImpl<ErpAccountMapper, ErpAccount> implements IErpAccountService {

    @Override
    public TableDataInfo<ErpAccount> queryPageList(ErpAccount account, PageQuery pageQuery) {
        LambdaQueryWrapper<ErpAccount> qw = new LambdaQueryWrapper<>();
        if (account.getAccountCode() != null && !account.getAccountCode().isEmpty()) {
            qw.like(ErpAccount::getAccountCode, account.getAccountCode());
        }
        if (account.getAccountName() != null && !account.getAccountName().isEmpty()) {
            qw.like(ErpAccount::getAccountName, account.getAccountName());
        }
        if (account.getAccountType() != null && !account.getAccountType().isEmpty()) {
            qw.eq(ErpAccount::getAccountType, account.getAccountType());
        }
        if (account.getStatus() != null) {
            qw.eq(ErpAccount::getStatus, account.getStatus());
        }
        qw.orderByAsc(ErpAccount::getAccountCode);
        return TableDataInfo.build(this.page(pageQuery.build(), qw));
    }

    @Override
    public List<ErpAccount> queryTreeList() {
        List<ErpAccount> all = this.list(new LambdaQueryWrapper<ErpAccount>()
                .eq(ErpAccount::getStatus, 1)
                .orderByAsc(ErpAccount::getAccountCode));
        
        // 构建树形结构
        return buildTree(all, null);
    }

    private List<ErpAccount> buildTree(List<ErpAccount> all, Long parentId) {
        return all.stream()
                .filter(acc -> (parentId == null && acc.getParentId() == null) || 
                              (parentId != null && parentId.equals(acc.getParentId())))
                .map(acc -> {
                    List<ErpAccount> children = buildTree(all, acc.getAccountId());
                    // 这里可以设置children，如果需要的话
                    return acc;
                })
                .collect(Collectors.toList());
    }

    @Override
    public ErpAccount getByCode(String accountCode) {
        return this.getOne(new LambdaQueryWrapper<ErpAccount>()
                .eq(ErpAccount::getAccountCode, accountCode)
                .last("LIMIT 1"));
    }
}

